<template>
	<!--index.wxml-->
	<view class="dialog login" :class="{show:show}">
		<view class="mask" @tap="cancel" bind:tap="cancel" catch:touchmove="emptyHandler"></view>
		<view class="container">
			<view class="close-box" @tap="cancel" bind:tap="cancel">
				<image class="close-img" src="../../static/sns/close@2x.png" />
			</view>
			<view class="header">
				<view class="logo-wrap">
					<image class="logo" src="../../static/sns/royole.png" mode="aspectFit" />
				</view>
			</view>
			<view class="p-name">欢迎登录柔宇星球</view>
		
	<!-- 			<button  class="submit-btn" open-type="getUserProfile" @getuserinfo="getUserProfile"  bindgetuserinfo="getUserProfile"> 获取头像昵称 </button>	
 -->			<button class="submit-btn" open-type="getUserInfo" @getuserinfo="getWechatUserInfo" bindgetuserinfo="getWechatUserInfo">
				<image src="../../static/sns/wechat.png" class="wechat-img" />微信一键登录
			</button>
			<view>
				<!-- <button class="phone-login" @tap="goToNav('/pages/register/otherPhone/index')">使用其他手机号注册</button> -->
			</view>
			<!-- <view wx:else class="info">获得你的手机号码</view> -->
			<view class="serve-info">点击登录柔宇星球，即表示已阅读并同意</view>
			<view class="serve-text">
				<view @tap="goToPage('https://www.royole.com/cn/privacy')">《隐私政策》</view>
				<view @tap="goToPage('https://www.royole.com/cn/agreement')">《用户协议》</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		$storage
	} from "@/utils";
	export default {
		data() {
			return {
				show: false,
				// 点击按钮需要等待 行为完成后 再进行下一步梳理逻辑
				canGetWechatUserinfoTag: true
			};
		},
		created: function() {
			console.log("onshow");
			uni.$on("login", () => {
				this.open();
			});
			uni.$on("login:close", () => {
				this.close(true);
			})
		},
		methods: {
			cancel() {
				this.close(true);
			},
			goToNav(url) {
				wx.navigateTo({
					url
				});
			},
			goToPage(url) {
				wx.navigateTo({
					url: '/pages/webview?url=' + encodeURI(url)
				});
			},
			close(force = false) {
				wx.showTabBar({});
				if (force === true) {
					this.show = false;
				}
			},
			open() {
				this.show = true;
			},
			async authLoginBySessionKey(params, encryptResult, passportUid) {
				return new Promise((resolve, reject) => {
					uni.checkSession({
						success: async () => {
							let res = await this.$u.api.decodeSessionKey({
								...params,
								encryptedData: encryptResult.encryptedData,
								iv: encryptResult.iv,
								signature: encryptResult.signature,
								passportUid,
							});
							uni.setStorageSync("openId", res.openid);
							if (res.statusCode == 500) {
								// 如果异常请求的时候
								throw new Error(res.message)
							}
							if (res.type === "alert") {
								if (res.message.indexOf("禁用") > -1) {
									wx.showModal({
										title: "提示",
										content: "您的账号已被禁用，申诉请联系柔宇科技公众号",
									});
								} else {
									wx.showModal({
										title: "提示",
										content: res.message,
									});
								}
								resolve("alert")
							} else if (res.type === "logined") {
								console.log('登陆成功，设置本地登陆相关信息')
								console.log(res);
								$storage.set("accessToken", res.token, {
									expires: res.expires_in,
								});
								$storage.set("passportToken", res.passport_token, {
									expires: res.expires_in,
								});
								$storage.remove("registerInfo");
								$storage.set("rouyu-app-id", res.app_id);
								$storage.set("rouyu-device-id", res.device_id);
								$storage.set("rouyu-user-id", res.uid_id);
								const user = await this.$u.api.getCurrentUser();
								let sex;
								if (user.sex == 1) {
									sex = '男'
								} else if (user.sex == 0) {
									sex = '女'
								} else {
									sex = '保密'
								}
								this.$$Rangers.config({
									user_unique_id: user.rouyu_uid,
									name: user.name,
									gender: sex,
									age: user.birth,
									country: '中国',
									province: user.location,
									city: '未知地址',
									mobile_phone: user.phone,
									mail: user.email,
									grade_level: '未设会员信息',
									first_channel: '小程序'
								});
								$storage.set("user", user);
								// 触发登陆之后的事件
								uni.$emit('after:login')
								resolve("logined");
							} else {
								$storage.set("registerInfo", res, {
									expires: 14400,
								});
								resolve("register");
							}
						},
						fail: () => {
							uni.login({
								success: (res) => {
									$storage.set("wechat-login-code", res.code, {
										expires: 1440,
									});
									uni.getUserInfo({
										lang: "zh_CN",
										success: async userInfo => {
											const codeRes = await this.$u.api.rouyuWechatCode(res.code);
											console.log(codeRes)
											const {
												session_key = "", claim: {
													uid = ""
												} = {}
											} = codeRes;
											// 未在passport注册
											await this.getUserBySessionKey({
													session_key,
													code: res.code,
												},
												userInfo,
												uid,
												false
											);
											this.canGetWechatUserinfoTag = true;
										}
									})
								},
							});
						}
					})
				})
			},
			// 获取用户头像信息
			getUserProfile(){
				debugger
				uni.getUserProfile({
					success:(res)=>{
						console.log(res);
					}
				})
			},
			/**
			 * res userInfo
			 */
			async getUserBySessionKey(params, res, passportUid) {
				wx.showLoading({
					title: "正在登录",
				});
				try {
					const loginType = await this.authLoginBySessionKey(
						params,
						res,
						passportUid
					);
					if (loginType == "logined") {
						$storage.remove("wechat-login-code");
						uni.$emit("after:login");
						this.close(true);
					} else if (loginType == "alert") {
						return
					} else {
						wx.navigateTo({
							url: "/pages/register/index",
						});
					}
				} catch (error) {
					console.log("登陆过程中出现异常，请求过程中抛出了500错误")
				}
				wx.hideLoading();
			},
			getWechatUserInfo() {
				// 数据埋点
				this.$$Rangers.event('login_oneClick', {
					platform: '小程序',
				})
				if (!this.canGetWechatUserinfoTag) return;
				this.canGetWechatUserinfoTag = false;
				debugger
				uni.login({
					success: (res) => {
						debugger
						$storage.set("wechat-login-code", res.code, {
							expires: 1440,
						});
						uni.getUserInfo({
							lang: "zh_CN",
							success: async userInfo => {
								debugger
								const codeRes = await this.$u.api.rouyuWechatCode(res.code);
								console.log(codeRes)
								const {
									session_key = "", claim: {
										uid = ""
									} = {}
								} = codeRes;
								// 未在passport注册
								await this.getUserBySessionKey({
										session_key,
										code: res.code,
									},
									userInfo,
									uid,
									false
								);
								this.canGetWechatUserinfoTag = true;
							}
						})
					},
				});
			},
		},
	};
</script>

<style lang="scss" scoped>
	@import "../../common";

	.dialog.login {
		position: fixed;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		display: flex;
		align-items: flex-end;
		// justify-content: center;
		opacity: 0;
		transition: opacity $transition-time, z-index 0 $transition-time;
		pointer-events: none;
		z-index: 9999999;

		&.show {
			z-index: $zindex-login-cover;
			opacity: 1;
			pointer-events: auto;
		}

		.mask {
			position: fixed;
			width: 100%;
			height: 100%;
			background-color: $mask-color;
		}

		.container {
			z-index: $zindex-login-dialog;
			display: flex;
			flex-direction: column;
			width: 100%;
			padding: 4 * $xl 1 * $xl;
			background-color: $bgcolor;
			border-radius: $border-radius;
			align-items: center;
			position: relative;

			.p-name {
				margin-top: 48upx;
				font-size: 36upx;
				font-weight: normal;
			}

			.close-box {
				position: absolute;
				right: 32upx;
				top: 38upx;
				width: 56.56upx;
				height: 56.56upx;
				padding: 10upx;

				.close-img {
					width: 100%;
					height: 100%;
				}
			}
		}

		.header {
			display: flex;
			flex-direction: column;
			align-items: center;
			font-size: $font-size-large;

			.logo-wrap {
				width: 144upx;
				height: 144upx;
				// margin-right: 40upx;
				overflow: hidden;
				//Instead of the line below you could use @include border-radius($radius, $vertical-radius)
				border-radius: 20upx;
			}

			.logo {
				width: 100%;
				height: 100%;
			}
		}

		.info {
			color: $info-color;
		}

		.submit-btn {
			width: 642upx;
			height: 88upx;
			margin-top: 60upx;
			border-radius: 44upx;
			display: flex;
			flex-direction: row;
			align-items: center;
			justify-content: center;
			color: #fff;
			background-color: #0046f5;
			font-size: 36upx;

			.wechat-img {
				width: 44upx;
				height: 34upx;
				margin: 0 18upx;
			}
		}

		.phone-login {
			color: #0046f5;
			font-size: 28upx;
			margin-top: 40upx;
			border: none;
			background-color: #fff;
		}

		.cancel-btn {
			width: 100%;
			margin-top: 60upx;
			color: $info-color;
			background-color: $disabled-color;
		}

		.serve-info {
			font-size: 22upx;
			margin-top: 50upx;
		}

		.serve-text {
			display: flex;
			flex-direction: row;
			align-items: center;
			justify-content: center;
			font-size: 22upx;
			color: #6079b8;
			margin-top: 10upx;
		}
	}

	button::after {
		border: none;
	}
</style>
